# coding=utf8

import csv
import numpy as np
import pandas as pd


class Preliminary:

    @staticmethod
    def open_write_csv(file_name='stu51a.csv'):
        with open(file_name, newline='', encoding='utf8', mode='wt') as f:
            f.writelines(['张明,18,100,"试验,已参加"'])

    @staticmethod
    def read_csv(file_name="stu51a.csv"):
        print(f"read csv file: {file_name}")
        with open(file_name, newline='', encoding='utf8') as f:
            csv_reader = csv.reader(f, delimiter=',', quotechar='|')
            for line in csv_reader:
                print(line)

    @staticmethod
    def write_csv(file_name="stu51b.csv"):
        data = [("李芳", 17, 100, "调查,未完成"),
                ("陈列", 22, 101, "实践,未参加")]
        with open(file_name, newline="", encoding='utf8', mode='wt') as f:
            csv_writer = csv.writer(f, delimiter=" ", quotechar="|")
            # 使用writerrow
            for line in data:
                csv_writer.writerow(line)
            # 也可以使用writerrows
            csv_writer.writerows(data)
        Preliminary.read_csv("stu51b.csv")

    @staticmethod
    def numpy_savetxt(file_name='stu51c.csv'):
        data = np.random.random((3, 3))
        print("save numpy array to {}:".format(file_name))
        print(data)
        np.savetxt(file_name, data, fmt="%.3f", newline='\r',
                   header="math phyics language", footer="c1 col2 col3",
                   )
        Preliminary.read_csv("stu51c.csv")

    @staticmethod
    def numpy_loadtxt(file_name='stu51c.csv'):
        print("read {} by numpy.loadtxt:".format(file_name))
        data = np.loadtxt(file_name)
        print(data)

    @staticmethod
    def pandas_read_csv():
        file_name = 'stu51b.csv'
        print("read {} by pandas.read_csv:".format(file_name))
        df = pd.read_csv(file_name,
                         header=None,
                         names=['name', 'age', 'score', 'etc'],
                         delimiter=' ')
        print(df)
        file_name = 'stu51c.csv'
        print("read {} by pandas.read_csv:".format(file_name))
        df = pd.read_csv(file_name,
                         comment='#',
                         names=['v1', 'v2', 'v3'],
                         delimiter=' ')
        print(df)

    @staticmethod
    def pandas_to_csv(df):
        df.to_csv('test4.csv', columns=['name', 'age', 'etc'], index=True, index_label='sno')


if __name__ == '__main__':
    Preliminary.read_csv()
    Preliminary.write_csv()
    Preliminary.numpy_savetxt()
    Preliminary.numpy_loadtxt()
    Preliminary.pandas_read_csv()
